import os
import sys
import json
import platform
from PyQt5.QtWidgets import (QWidget, QVBoxLayout, QHBoxLayout, QPushButton, QLabel, 
                            QGroupBox, QTextEdit, QMessageBox, QTableWidget, QHeaderView,
                            QAbstractItemView, QTableWidgetItem, QComboBox)
from PyQt5.QtCore import Qt, pyqtSignal, pyqtSlot, QThread
import sqlite3

# 添加cursor-free-vip目录到搜索路径
cursor_free_vip_path = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(__file__))), "cursor-free-vip")
sys.path.append(cursor_free_vip_path)

# 直接导入模块
from cursor_acc_info import get_token, UsageManager, display_account_info
from reset_machine_manual import MachineIDResetter, get_cursor_machine_id_path
from cursor_auth import CursorAuth

# 导入我们自己的功能模块
from modules.utils.register_utils import load_registered_accounts, save_registered_accounts

# 导入我们自己的配置
from config.cursor_vip_config import get_config

class ResetMachineIDThread(QThread):
    """用于重置机器码的线程"""
    finished_signal = pyqtSignal(bool, str)
    
    def run(self):
        try:
            # 创建机器码重置器
            resetter = MachineIDResetter(None)
            # 重置机器码
            success = resetter.reset_machine_ids()
            
            if success:
                self.finished_signal.emit(True, "机器码重置成功")
            else:
                self.finished_signal.emit(False, "机器码重置失败")
                
        except Exception as e:
            self.finished_signal.emit(False, f"重置机器码时出错: {str(e)}")


class AccountSwitchThread(QThread):
    """用于切换账号的线程"""
    finished_signal = pyqtSignal(bool, str)
    
    def __init__(self, email, password, token):
        super().__init__()
        self.email = email
        self.password = password
        self.token = token
    
    def run(self):
        try:
            # 创建CursorAuth对象
            auth = CursorAuth()
            # 更新认证信息
            success = auth.update_auth(
                email=self.email,
                access_token=self.token
            )
            
            if success:
                self.finished_signal.emit(True, f"账号切换成功: {self.email}")
            else:
                self.finished_signal.emit(False, f"账号切换失败: {self.email}")
                
        except Exception as e:
            self.finished_signal.emit(False, f"切换账号时出错: {str(e)}")


class CursorToolsTab(QWidget):
    """Cursor工具标签页"""
    
    def __init__(self, parent=None):
        super().__init__(parent)
        self.registered_accounts = {}
        self.current_token = None
        self.current_email = None
        self.current_usage = None
        self.init_ui()
        # 加载已注册账号
        self.load_registered_accounts()
        # 更新当前账号信息
        self.update_current_account_info()
        
    def init_ui(self):
        """初始化UI"""
        layout = QVBoxLayout(self)
        
        # 当前账号信息面板
        self.create_current_account_panel(layout)
        
        # 操作按钮面板
        self.create_operations_panel(layout)
        
        # 账号列表面板
        self.create_accounts_table_panel(layout)
        
    def create_current_account_panel(self, parent_layout):
        """创建当前账号信息面板"""
        group_box = QGroupBox("当前登录账号信息")
        layout = QVBoxLayout()
        
        # 当前账号信息面板
        info_layout = QVBoxLayout()
        
        # 创建基本信息标签
        self.email_label = QLabel("邮箱: 正在加载...")
        self.machine_id_label = QLabel("机器码: 正在加载...")
        self.premium_usage_label = QLabel("高级额度: 正在加载...")
        self.basic_usage_label = QLabel("基础额度: 正在加载...")
        self.subscription_label = QLabel("订阅类型: 正在加载...")
        
        # 添加标签到布局
        info_layout.addWidget(self.email_label)
        info_layout.addWidget(self.machine_id_label)
        info_layout.addWidget(self.premium_usage_label)
        info_layout.addWidget(self.basic_usage_label)
        info_layout.addWidget(self.subscription_label)
        
        layout.addLayout(info_layout)
        
        # 刷新按钮
        refresh_button = QPushButton("刷新信息")
        refresh_button.clicked.connect(self.update_current_account_info)
        layout.addWidget(refresh_button)
        
        group_box.setLayout(layout)
        parent_layout.addWidget(group_box)
        
    def create_operations_panel(self, parent_layout):
        """创建操作按钮面板"""
        group_box = QGroupBox("账号操作")
        layout = QHBoxLayout()
        
        # 切换选中账号按钮
        switch_account_button = QPushButton("切换到选中账号")
        switch_account_button.clicked.connect(self.switch_account)
        layout.addWidget(switch_account_button)
        
        # 重置机器码按钮
        reset_machine_button = QPushButton("重置机器码")
        reset_machine_button.clicked.connect(self.reset_machine_id)
        layout.addWidget(reset_machine_button)
        
        group_box.setLayout(layout)
        parent_layout.addWidget(group_box)
        
    def create_accounts_table_panel(self, parent_layout):
        """创建账号列表面板"""
        group_box = QGroupBox("已注册账号列表")
        layout = QVBoxLayout()
        
        # 创建表格
        self.accounts_table = QTableWidget()
        self.accounts_table.setColumnCount(5)
        self.accounts_table.setHorizontalHeaderLabels(["邮箱", "Cursor密码", "Token", "已使用", "总额度"])
        self.accounts_table.setSelectionBehavior(QAbstractItemView.SelectRows)
        self.accounts_table.setSelectionMode(QAbstractItemView.SingleSelection)
        self.accounts_table.horizontalHeader().setSectionResizeMode(0, QHeaderView.Stretch)  # 邮箱列自适应宽度
        self.accounts_table.horizontalHeader().setSectionResizeMode(2, QHeaderView.Stretch)  # Token列自适应宽度
        
        layout.addWidget(self.accounts_table)
        
        group_box.setLayout(layout)
        parent_layout.addWidget(group_box)
        
    def load_registered_accounts(self):
        """加载已注册账号"""
        self.registered_accounts = load_registered_accounts()
        self.update_accounts_table()
        
    def update_accounts_table(self):
        """更新账号表格"""
        # 清空表格
        self.accounts_table.setRowCount(0)
        
        # 添加账号到表格
        row = 0
        for email, account in self.registered_accounts.items():
            if account.get("token") and account.get("cursor_password"):
                # 添加一行
                self.accounts_table.insertRow(row)
                
                # 设置各列数据
                self.accounts_table.setItem(row, 0, QTableWidgetItem(email))
                self.accounts_table.setItem(row, 1, QTableWidgetItem(account.get("cursor_password", "")))
                
                # Token列显示部分...
                token = account.get("token", "")
                token_display = token[:10] + "..." if token else ""
                self.accounts_table.setItem(row, 2, QTableWidgetItem(token_display))
                
                # 使用状态列(暂时空白)
                self.accounts_table.setItem(row, 3, QTableWidgetItem("未知"))
                self.accounts_table.setItem(row, 4, QTableWidgetItem("未知"))
                
                # 如果是当前账号，高亮显示
                if self.current_email == email:
                    for col in range(self.accounts_table.columnCount()):
                        item = self.accounts_table.item(row, col)
                        if item:
                            item.setBackground(Qt.green)
                
                row += 1
    
    def update_current_account_info(self):
        """更新当前账号信息"""
        try:
            # 获取当前token
            self.current_token = get_token()
            if not self.current_token:
                self.email_label.setText("邮箱: 未登录")
                self.machine_id_label.setText("机器码: 未知")
                self.premium_usage_label.setText("高级额度: 未知")
                self.basic_usage_label.setText("基础额度: 未知")
                self.subscription_label.setText("订阅类型: 未知")
                return
                
            # 获取使用情况
            usage_data = UsageManager.get_usage(self.current_token)
            if usage_data:
                self.current_usage = usage_data
                self.premium_usage_label.setText(f"高级额度: {usage_data['premium_usage']}/{usage_data['max_premium_usage']}")
                self.basic_usage_label.setText(f"基础额度: {usage_data['basic_usage']}/{usage_data['max_basic_usage']}")
            else:
                self.premium_usage_label.setText("高级额度: 获取失败")
                self.basic_usage_label.setText("基础额度: 获取失败")
            
            # 获取订阅信息
            subscription_data = UsageManager.get_stripe_profile(self.current_token)
            if subscription_data:
                subscription_type = subscription_data.get("membershipType", "未知")
                subscription_status = subscription_data.get("subscriptionStatus", "未知")
                self.subscription_label.setText(f"订阅类型: {subscription_type} ({subscription_status})")
            else:
                self.subscription_label.setText("订阅类型: 获取失败")
                
            # 找到当前邮箱
            for email, account in self.registered_accounts.items():
                if account.get("token") == self.current_token:
                    self.current_email = email
                    self.email_label.setText(f"邮箱: {email}")
                    break
            else:
                # 未找到匹配的token
                self.email_label.setText("邮箱: 未能识别")
                
            # 获取机器码
            machine_id_path = get_cursor_machine_id_path()
            if os.path.exists(machine_id_path):
                with open(machine_id_path, 'r', encoding='utf-8') as f:
                    machine_id = f.read().strip()
                self.machine_id_label.setText(f"机器码: {machine_id}")
            else:
                self.machine_id_label.setText("机器码: 未找到")
                
            # 更新账号表格，高亮当前账号
            self.update_accounts_table()
            
        except Exception as e:
            error_message = str(e)
            if "file is not a database" in error_message or "database disk image is malformed" in error_message:
                # 数据库文件格式错误，提示用户重建数据库
                reply = QMessageBox.question(
                    self,
                    "数据库错误",
                    "检测到数据库文件已损坏，是否尝试修复?\n(这将备份并重建数据库文件)",
                    QMessageBox.Yes | QMessageBox.No,
                    QMessageBox.Yes
                )
                
                if reply == QMessageBox.Yes:
                    self.repair_database()
                else:
                    QMessageBox.warning(self, "错误", "由于数据库损坏，账号信息无法获取。您可以稍后通过点击'刷新信息'按钮重试修复。")
            else:
                QMessageBox.warning(self, "错误", f"获取账号信息时出错: {error_message}")
    
    def repair_database(self):
        """尝试修复损坏的数据库文件"""
        try:
            # 获取配置路径
            from cursor_acc_info import get_token_from_config
            paths = get_token_from_config()
            
            if not paths:
                QMessageBox.warning(self, "错误", "无法获取数据库路径配置")
                return
            
            # 备份原始文件
            import shutil
            from datetime import datetime
            
            sqlite_path = paths['sqlite_path']
            backup_path = f"{sqlite_path}.bak.{datetime.now().strftime('%Y%m%d%H%M%S')}"
            
            if os.path.exists(sqlite_path):
                try:
                    shutil.copy2(sqlite_path, backup_path)
                    QMessageBox.information(self, "备份成功", f"原始数据库已备份到: {backup_path}")
                except Exception as e:
                    QMessageBox.warning(self, "备份失败", f"无法备份数据库: {str(e)}")
                    return
                
                # 删除损坏的数据库
                try:
                    os.remove(sqlite_path)
                except Exception as e:
                    QMessageBox.critical(self, "错误", f"无法删除损坏的数据库文件: {str(e)}\n请手动删除: {sqlite_path}")
                    return
            
            # 创建新数据库
            import sqlite3
            try:
                conn = sqlite3.connect(sqlite_path)
                cursor = conn.cursor()
                cursor.execute('''
                    CREATE TABLE IF NOT EXISTS ItemTable (
                        key TEXT PRIMARY KEY,
                        value TEXT
                    )
                ''')
                conn.commit()
                conn.close()
                
                # 设置权限
                if sys.platform != "win32":  # 非Windows系统
                    os.chmod(sqlite_path, 0o644)
                
                QMessageBox.information(self, "成功", "数据库已重建，请重启Cursor并再次登录您的账号")
                self.update_current_account_info()
                
            except Exception as e:
                QMessageBox.critical(self, "错误", f"创建新数据库失败: {str(e)}")
                return
            
        except Exception as e:
            QMessageBox.critical(self, "错误", f"修复过程中发生错误: {str(e)}")
    
    def switch_account(self):
        """切换到选中账号"""
        try:
            selected_rows = self.accounts_table.selectedItems()
            if not selected_rows:
                QMessageBox.warning(self, "警告", "请先选择一个账号")
                return
                
            # 获取选中行
            row = selected_rows[0].row()
            email = self.accounts_table.item(row, 0).text()
            
            # 获取账号信息
            account = self.registered_accounts.get(email)
            if not account:
                QMessageBox.warning(self, "错误", f"找不到账号信息: {email}")
                return
                
            # 确认切换
            reply = QMessageBox.question(
                self, 
                "确认", 
                f"确定要切换到账号 {email} 吗？\n此操作会退出当前登录账号。",
                QMessageBox.Yes | QMessageBox.No, 
                QMessageBox.No
            )
            
            if reply != QMessageBox.Yes:
                return
                
            # 创建线程切换账号
            self.switch_thread = AccountSwitchThread(
                email=email,
                password=account.get("cursor_password", ""),
                token=account.get("token", "")
            )
            self.switch_thread.finished_signal.connect(self.on_account_switch_finished)
            self.switch_thread.start()
            
            # 禁用按钮
            for i in range(self.layout().count()):
                widget = self.layout().itemAt(i).widget()
                if isinstance(widget, QGroupBox):
                    widget.setEnabled(False)
                    
        except sqlite3.DatabaseError as e:
            # 处理数据库格式错误
            error_message = str(e)
            if "file is not a database" in error_message or "database disk image is malformed" in error_message:
                reply = QMessageBox.question(
                    self,
                    "数据库错误",
                    "检测到数据库文件已损坏，是否尝试修复?\n(这将备份并重建数据库文件)",
                    QMessageBox.Yes | QMessageBox.No,
                    QMessageBox.Yes
                )
                
                if reply == QMessageBox.Yes:
                    self.repair_database()
                else:
                    QMessageBox.warning(self, "错误", "由于数据库损坏，无法切换账号")
            else:
                QMessageBox.warning(self, "数据库错误", f"切换账号时发生数据库错误: {error_message}")
                
        except Exception as e:
            QMessageBox.warning(self, "错误", f"切换账号时发生意外错误: {str(e)}")
    
    @pyqtSlot(bool, str)
    def on_account_switch_finished(self, success, message):
        """账号切换完成的回调"""
        # 启用按钮
        for i in range(self.layout().count()):
            widget = self.layout().itemAt(i).widget()
            if isinstance(widget, QGroupBox):
                widget.setEnabled(True)
        
        if success:
            QMessageBox.information(self, "成功", message)
            # 更新当前账号信息
            self.update_current_account_info()
        else:
            QMessageBox.warning(self, "错误", message)
    
    def reset_machine_id(self):
        """重置机器码"""
        reply = QMessageBox.question(
            self, 
            "确认", 
            "确定要重置机器码吗？\n此操作会修改系统相关标识，重置后需要重启Cursor。",
            QMessageBox.Yes | QMessageBox.No, 
            QMessageBox.No
        )
        
        if reply != QMessageBox.Yes:
            return
            
        # 创建线程重置机器码
        self.reset_thread = ResetMachineIDThread()
        self.reset_thread.finished_signal.connect(self.on_reset_finished)
        self.reset_thread.start()
        
        # 禁用按钮
        for i in range(self.layout().count()):
            widget = self.layout().itemAt(i).widget()
            if isinstance(widget, QGroupBox):
                widget.setEnabled(False)
    
    @pyqtSlot(bool, str)
    def on_reset_finished(self, success, message):
        """重置机器码完成的回调"""
        # 启用按钮
        for i in range(self.layout().count()):
            widget = self.layout().itemAt(i).widget()
            if isinstance(widget, QGroupBox):
                widget.setEnabled(True)
        
        if success:
            QMessageBox.information(self, "成功", message + "\n请重启Cursor以应用更改")
            # 更新当前账号信息
            self.update_current_account_info()
        else:
            QMessageBox.warning(self, "错误", message) 